#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "httpauth.h"
//#include "md5.h"

//来自于博文 https://blog.csdn.net/sinat_16643223/article/details/120227764


//*********************************************放的md5.c的内容*************************************************

/*
 *	md5.c
 *
 *	Implements	the  MD5 Message-Digest Algorithm as specified in
 *	RFC  1321.	This  implementation  is a simple one, in that it
 *	needs  every  input  byte  to  be  buffered  before doing any
 *	calculations.  I  do  not  expect  this  file  to be used for
 *	general  purpose  MD5'ing  of large amounts of data, only for
 *	generating hashed passwords from limited input.
 *
 *	Sverre H. Huseby <sverrehu@online.no>
 *
 *	Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
 *	Portions Copyright (c) 1994, Regents of the University of California
 *
 *  This file is imported from PostgreSQL 8.1.3., and modified by
 *  Taiki Yamaguchi <yamaguchi@sraoss.co.jp>
 *
 * IDENTIFICATION
 *	$Header$
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


//我直接把md5.h的头文件的内容复制进来了，就不include头文件了
/*-------------------------------------------------------------------------
 *
 * md5.h
 *	  Interface to md5.c
 *
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * $Header$
 *
 *-------------------------------------------------------------------------
 */

/*
 *  This file is imported from PostgreSQL 8.1.3.
 *  Modified by Taiki Yamaguchi <yamaguchi@sraoss.co.jp>
 */

#ifndef MD5_H
#define MD5_H

#define MD5_PASSWD_LEN 32
typedef unsigned char uint8;	/* == 8 bits */
typedef unsigned int uint32;	/* == 32 bits */
typedef char bool;
#define true ((bool) 1)
#define TRUE ((bool) 1)
#define false ((bool) 0)
#define FALSE ((bool) 0)

//extern 
int md5_hash(const void *buff, size_t len, char *hexsum);
//extern 
int md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf);

#endif


#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21

#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))

#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))

#define FF(a, b, c, d, x, s, ac) { \
(a) += F((b), (c), (d)) + (x) + (uint32)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}

#define GG(a, b, c, d, x, s, ac) { \
(a) += G((b), (c), (d)) + (x) + (uint32)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}

#define HH(a, b, c, d, x, s, ac) { \
(a) += H((b), (c), (d)) + (x) + (uint32)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}

#define II(a, b, c, d, x, s, ac) { \
(a) += I((b), (c), (d)) + (x) + (uint32)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}

const uint32 T[64] =
{
	0xd76aa478,	0xe8c7b756,	0x242070db,	0xc1bdceee,	0xf57c0faf,	0x4787c62a,	0xa8304613,	0xfd469501,
	0x698098d8,	0x8b44f7af,	0xffff5bb1,	0x895cd7be,	0x6b901122,	0xfd987193,	0xa679438e,	0x49b40821,

	0xf61e2562,	0xc040b340,	0x265e5a51,	0xe9b6c7aa,	0xd62f105d,	0x02441453,	0xd8a1e681,	0xe7d3fbc8,
	0x21e1cde6,	0xc33707d6,	0xf4d50d87,	0x455a14ed,	0xa9e3e905,	0xfcefa3f8,	0x676f02d9,	0x8d2a4c8a,

	0xfffa3942,	0x8771f681,	0x6d9d6122,	0xfde5380c,	0xa4beea44,	0x4bdecfa9,	0xf6bb4b60,	0xbebfbc70,
	0x289b7ec6,	0xeaa127fa,	0xd4ef3085,	0x04881d05,	0xd9d4d039,	0xe6db99e5,	0x1fa27cf8,	0xc4ac5665,

	0xf4292244,	0x432aff97,	0xab9423a7,	0xfc93a039,	0x655b59c3,	0x8f0ccc92,	0xffeff47d,	0x85845dd1,
	0x6fa87e4f,	0xfe2ce6e0,	0xa3014314,	0x4e0811a1,	0xf7537e82,	0xbd3af235,	0x2ad7d2bb,	0xeb86d391
};


/*
 *	PRIVATE FUNCTIONS
 */


/*
 *	The returned array is allocated using malloc.  the caller should free it
 *	when it is no longer needed.
 */
static uint8 *
createPaddedCopyWithLength(uint8 *b, uint32 *l)
{
	/*
	 * uint8 *b  - message to be digested
	 * uint32 *l - length of b
	 */
	uint8	   *ret;
	uint32		q;
	uint32		len,
				newLen448;
	uint32		len_high,
				len_low;		/* 64-bit value split into 32-bit sections */

	len = ((b == NULL) ? 0 : *l);
	newLen448 = len + 64 - (len % 64) - 8;
	if (newLen448 <= len)
		newLen448 += 64;

	*l = newLen448 + 8;
	if ((ret = (uint8 *) malloc(sizeof(uint8) * *l)) == NULL)
		return NULL;

	if (b != NULL)
		memcpy(ret, b, sizeof(uint8) * len);

	/* pad */
	ret[len] = 0x80;
	for (q = len + 1; q < newLen448; q++)
		ret[q] = 0x00;

	/* append length as a 64 bit bitcount */
	len_low = len;
	/* split into two 32-bit values */
	/* we only look at the bottom 32-bits */
	len_high = len >> 29;
	len_low <<= 3;
	q = newLen448;
	ret[q++] = (len_low & 0xff);
	len_low >>= 8;
	ret[q++] = (len_low & 0xff);
	len_low >>= 8;
	ret[q++] = (len_low & 0xff);
	len_low >>= 8;
	ret[q++] = (len_low & 0xff);
	ret[q++] = (len_high & 0xff);
	len_high >>= 8;
	ret[q++] = (len_high & 0xff);
	len_high >>= 8;
	ret[q++] = (len_high & 0xff);
	len_high >>= 8;
	ret[q] = (len_high & 0xff);

	return ret;
}

static void
doTheRounds(uint32 X[16], uint32 state[4])
{
	uint32		a,
				b,
				c,
				d;

	a = state[0];
	b = state[1];
	c = state[2];
	d = state[3];

	/* round 1 */
	FF(a, b, c, d, X[ 0], S11, T[ 0]);
	FF(d, a, b, c, X[ 1], S12, T[ 1]);
	FF(c, d, a, b, X[ 2], S13, T[ 2]);
	FF(b, c, d, a, X[ 3], S14, T[ 3]);
	FF(a, b, c, d, X[ 4], S11, T[ 4]);
	FF(d, a, b, c, X[ 5], S12, T[ 5]);
	FF(c, d, a, b, X[ 6], S13, T[ 6]);
	FF(b, c, d, a, X[ 7], S14, T[ 7]);
	FF(a, b, c, d, X[ 8], S11, T[ 8]);
	FF(d, a, b, c, X[ 9], S12, T[ 9]);
	FF(c, d, a, b, X[10], S13, T[10]);
	FF(b, c, d, a, X[11], S14, T[11]);
	FF(a, b, c, d, X[12], S11, T[12]);
	FF(d, a, b, c, X[13], S12, T[13]);
	FF(c, d, a, b, X[14], S13, T[14]);
	FF(b, c, d, a, X[15], S14, T[15]);

	GG(a, b, c, d, X[ 1], S21, T[16]);
	GG(d, a, b, c, X[ 6], S22, T[17]);
	GG(c, d, a, b, X[11], S23, T[18]);
	GG(b, c, d, a, X[ 0], S24, T[19]);
	GG(a, b, c, d, X[ 5], S21, T[20]);
	GG(d, a, b, c, X[10], S22, T[21]);
	GG(c, d, a, b, X[15], S23, T[22]);
	GG(b, c, d, a, X[ 4], S24, T[23]);
	GG(a, b, c, d, X[ 9], S21, T[24]);
	GG(d, a, b, c, X[14], S22, T[25]);
	GG(c, d, a, b, X[ 3], S23, T[26]);
	GG(b, c, d, a, X[ 8], S24, T[27]);
	GG(a, b, c, d, X[13], S21, T[28]);
	GG(d, a, b, c, X[ 2], S22, T[29]);
	GG(c, d, a, b, X[ 7], S23, T[30]);
	GG(b, c, d, a, X[12], S24, T[31]);

	HH(a, b, c, d, X[ 5], S31, T[32]);
	HH(d, a, b, c, X[ 8], S32, T[33]);
	HH(c, d, a, b, X[11], S33, T[34]);
	HH(b, c, d, a, X[14], S34, T[35]);
	HH(a, b, c, d, X[ 1], S31, T[36]);
	HH(d, a, b, c, X[ 4], S32, T[37]);
	HH(c, d, a, b, X[ 7], S33, T[38]);
	HH(b, c, d, a, X[10], S34, T[39]);
	HH(a, b, c, d, X[13], S31, T[40]);
	HH(d, a, b, c, X[ 0], S32, T[41]);
	HH(c, d, a, b, X[ 3], S33, T[42]);
	HH(b, c, d, a, X[ 6], S34, T[43]);
	HH(a, b, c, d, X[ 9], S31, T[44]);
	HH(d, a, b, c, X[12], S32, T[45]);
	HH(c, d, a, b, X[15], S33, T[46]);
	HH(b, c, d, a, X[ 2], S34, T[47]);

	II(a, b, c, d, X[ 0], S41, T[48]);
	II(d, a, b, c, X[ 7], S42, T[49]);
	II(c, d, a, b, X[14], S43, T[50]);
	II(b, c, d, a, X[ 5], S44, T[51]);
	II(a, b, c, d, X[12], S41, T[52]);
	II(d, a, b, c, X[ 3], S42, T[53]);
	II(c, d, a, b, X[10], S43, T[54]);
	II(b, c, d, a, X[ 1], S44, T[55]);
	II(a, b, c, d, X[ 8], S41, T[56]);
	II(d, a, b, c, X[15], S42, T[57]);
	II(c, d, a, b, X[ 6], S43, T[58]);
	II(b, c, d, a, X[13], S44, T[59]);
	II(a, b, c, d, X[ 4], S41, T[60]);
	II(d, a, b, c, X[11], S42, T[61]);
	II(c, d, a, b, X[ 2], S43, T[62]);
	II(b, c, d, a, X[ 9], S44, T[63]);

	state[0] += a;
	state[1] += b;
	state[2] += c;
	state[3] += d;
}

static int
calculateDigestFromBuffer(uint8 *b, uint32 len, uint8 sum[16])
{
	/*
	 * uint8 *b      - message to be digested
	 * uint32 len    - length of b
	 * uint8 sum[16] - md5 digest calculated from b
	 */

	register uint32 i,
				j,
				k,
				newI;
	uint32		l;
	uint8	   *input;
	register uint32 *wbp;
	uint32		workBuff[16],
				state[4];

	l = len;

	state[0] = 0x67452301;
	state[1] = 0xEFCDAB89;
	state[2] = 0x98BADCFE;
	state[3] = 0x10325476;

	if ((input = createPaddedCopyWithLength(b, &l)) == NULL)
		return 0;

	for (i = 0;;)
	{
		if ((newI = i + 16 * 4) > l)
			break;
		k = i + 3;
		for (j = 0; j < 16; j++)
		{
			wbp = (workBuff + j);
			*wbp = input[k--];
			*wbp <<= 8;
			*wbp |= input[k--];
			*wbp <<= 8;
			*wbp |= input[k--];
			*wbp <<= 8;
			*wbp |= input[k];
			k += 7;
		}
		doTheRounds(workBuff, state);
		i = newI;
	}
	free(input);

	j = 0;
	for (i = 0; i < 4; i++)
	{
		k = state[i];
		sum[j++] = (k & 0xff);
		k >>= 8;
		sum[j++] = (k & 0xff);
		k >>= 8;
		sum[j++] = (k & 0xff);
		k >>= 8;
		sum[j++] = (k & 0xff);
	}
	return 1;
}

static void
bytesToHex(uint8 b[16], char *s)
{
	static const char *hex = "0123456789abcdef";
	int			q,
				w;

	for (q = 0, w = 0; q < 16; q++)
	{
		s[w++] = hex[(b[q] >> 4) & 0x0F];
		s[w++] = hex[b[q] & 0x0F];
	}
	s[w] = '\0';
}

/*
 *	PUBLIC FUNCTIONS
 */

/*
 *	pool_md5_hash
 *
 *	Calculates the MD5 sum of the bytes in a buffer.
 *
 *	SYNOPSIS	  int md5_hash(const void *buff, size_t len, char *hexsum)
 *
 *	INPUT		  buff	  the buffer containing the bytes that you want
 *						  the MD5 sum of.
 *				  len	  number of bytes in the buffer.
 *
 *	OUTPUT		  hexsum  the MD5 sum as a '\0'-terminated string of
 *						  hexadecimal digits.  an MD5 sum is 16 bytes long.
 *						  each byte is represented by two heaxadecimal
 *						  characters.  you thus need to provide an array
 *						  of 33 characters, including the trailing '\0'.
 *
 *	RETURNS		  false on failure (out of memory for internal buffers) or
 *				  true on success.
 *
 *	STANDARDS	  MD5 is described in RFC 1321.
 *
 *	AUTHOR		  Sverre H. Huseby <sverrehu@online.no>
 *  MODIFIED by   Taiki Yamaguchi <yamaguchi@sraoss.co.jp>
 *
 */
int
md5_hash(const void *buff, size_t len, char *hexsum)
{
	uint8		sum[16];

	if (!calculateDigestFromBuffer((uint8 *) buff, len, sum))
		return 0;				/* failed */

	bytesToHex(sum, hexsum);
	return 1;					/* success */
}

/*
 * Computes MD5 checksum of "passwd" (a null-terminated string) followed
 * by "salt" (which need not be null-terminated).
 *
 * Output format is a 32-hex-digit MD5 checksum.
 * Hence, the output buffer "buf" must be at least 33 bytes long.
 *
 * Returns 1 if okay, 0 on error (out of memory).
 */
int
md5_encrypt(const char *passwd, const char *salt, size_t salt_len,
			   char *buf)
{
	size_t passwd_len = strlen(passwd);
	char *crypt_buf = malloc(passwd_len + salt_len);
	int ret;

	if (!crypt_buf)
		return 0;				/* failed */

	/*
	 * Place salt at the end because it may be known by users trying to crack
	 * the MD5 output.
	 */
	strcpy(crypt_buf, passwd);
	memcpy(crypt_buf + passwd_len, salt, salt_len);

	ret = md5_hash(crypt_buf, passwd_len + salt_len, buf);

	free(crypt_buf);

	return ret;
}

/*
 * Computes MD5 checksum of "passwd" (a null-terminated string) followed
 * by "salt" (which need not be null-terminated).
 *
 * Output format is "md5" followed by a 32-hex-digit MD5 checksum.
 * Hence, the output buffer "buf" must be at least 36 bytes long.
 *
 * Returns TRUE if okay, FALSE on error (out of memory).
 */
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len,
			   char *buf)
{
	size_t		passwd_len = strlen(passwd);

	/* +1 here is just to avoid risk of unportable malloc(0) */
	char	   *crypt_buf = malloc(passwd_len + salt_len + 1);
	bool		ret;

	if (!crypt_buf)
		return false;

	/*
	 * Place salt at the end because it may be known by users trying to crack
	 * the MD5 output.
	 */
	memcpy(crypt_buf, passwd, passwd_len);
	memcpy(crypt_buf + passwd_len, salt, salt_len);

	strcpy(buf, "md5");
	ret = md5_hash(crypt_buf, passwd_len + salt_len, buf + 3);

	free(crypt_buf);

	return ret;
}








//***********************************************放的md5.c的内容******************************************************





 
#define IPSTR "192.168.42.108" //服务器IP地址;
#define PORT 80
//#define PORT 443
#define BUFSIZE 1024


 //函数参数：生成随机字符串的长度
    //返回值：成功返回随机字符串
char *createRandomNum(int N)
{
    int flag;
    int k=0,j=0;
    char *random_str = (char*)malloc(N+1);
    random_str[0] = '\0';
    //1970到现在的时间sec作为种子
    unsigned int seed = (unsigned)time(NULL);
    srand(seed);
    for(j=0;j<N;j++)
    {
    unsigned int random_num = rand();
    flag = random_num%3;
    if(flag == 0)
    {
    random_str[k++]='0'+random_num%10;
    }
    else if(flag == 1)
    {
    random_str[k++]='a'+random_num%26;
    }
    else if(flag == 2)
    {
    random_str[k++]='A'+random_num%26;
    }
    srand(random_num);
    }
    random_str[k]='\0';
    return random_str;
}



    //函数功能：获取子串
 
    //函数参数：source目标字符串；start_str开始字符串；end_chr结束字符
 
    //返回值：成功返回该子串，失败返回NULL
 
char* GetTargetStr(const char*source,char*start_str,char end_chr)
{
 
    char *p_start = NULL;
 
    char *p_end = NULL;
 
    p_start = strstr(source,start_str);
 
    p_start += strlen(start_str);
 
    p_end = strchr(p_start,end_chr);
 
    char *ret = NULL;
 
    if(p_end != NULL)
 
    {
 
    ret = (char*)malloc(p_end - p_start +1);
 
    ret[p_end - p_start] = '\0';
 
    memcpy(ret,p_start,p_end - p_start);
 
    }
 
    return ret;
 
    //free(ret);
}

//下面函数复制自：https://blog.csdn.net/sujudz/article/details/7933211

char* substring(char* ch,int pos,int length)
{
    char* pch=ch;
//定义一个字符指针，指向传递进来的ch地址。
    char* subch=calloc(sizeof(char),length+1);
//通过calloc来分配一个length长度的字符数组，返回的是字符指针。
    int i;
//只有在C99下for循环中才可以声明变量，这里写在外面，提高兼容性。
    pch=pch+pos;
//是pch指针指向pos位置。
    for(i=0;i<length;i++)
    {
        subch[i]=*(pch++);
//循环遍历赋值数组。
    }
    subch[length]='\0';//加上字符串结束符。
    return subch;		//返回分配的字符数组地址。
}



 
int main(int argc, char **argv)
{
        int sockfd, ret, i, h;
        struct sockaddr_in servaddr;
        char str1[4096], str2[4096], str1_1[4096], buf[BUFSIZE], *str;
        socklen_t len;
        fd_set   t_set1;
        struct timeval  tv;
         
         //创建套接字
        if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
                printf("创建网络连接失败,本线程即将终止---socket error!\n");
                exit(0);
        };
 
        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(PORT);
        if (inet_pton(AF_INET, IPSTR, &servaddr.sin_addr) <= 0 ){
                printf("创建网络连接失败,本线程即将终止--inet_pton error!\n");
                exit(0);
        };
 
        if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
                printf("连接到服务器失败,connect error!\n");
                exit(0);
        }
        printf("与远端建立了连接\n");
        memset(str2, 0, 4096);
        strcat(str2, "theDataToPost");
        str=(char *)malloc(128);
        len = strlen(str2);
        sprintf(str, "%d", len);
 
        memset(str1, 0, 4096);
        //strcat(str1, "GET /ymnets/p/6255674.html HTTP/1.1\n");
        //strcat(str1, "Host: www.cnblogs.com\n");
        strcat(str1, "GET /cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20 HTTP/1.1\n");
        strcat(str1, "Host: 192.168.42.108\n");
        //strcat(str1, "Content-Type: text/html\n");
        //strcat(str1, "Content-Length: ");
        strcat(str1,"Authorization: Digest username=\"admin\",realm=\"Login to FH0427PAZ00039\",nonce=\"1276697283\",uri=\"/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20\",algorithm=\"MD5\",qop=auth,nc=00000001,cnonce=\"522e610057899296\",response=\"9ca7eb4a60e2c65ae70d28cfee327167\",opaque=\"ecd96bfa32ed521cda6e9a8ed1701e6b3ef687d0\"\n");
        //strcat(str1,"Authenticate: Digest username=\"admin\",realm=\"Login to FH0427PAZ00039\",nonce=\"1276697283\",uri=\"/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20\",algorithm=\"MD5\",qop=auth,nc=00000001,cnonce=\"522e610057899296\",response=\"9ca7eb4a60e2c65ae70d28cfee327167\",opaque=\"ecd96bfa32ed521cda6e9a8ed1701e6b3ef687d0\"\n");
        //strcat(str1, str);
        //strcat(str1, "\n\n");
 
        //strcat(str1, str2);
        strcat(str1, "\r\n\r\n");
        printf("%s\n",str1);
 
        ret = write(sockfd,str1,strlen(str1));
        if (ret < 0) {
                printf("发送失败！错误代码是%d，错误信息是'%s'\n",errno, strerror(errno));
                exit(0);
        }else{
                printf("消息发送成功，共发送了%d个字节！\n\n", ret);
        }
 
        FD_ZERO(&t_set1);
        FD_SET(sockfd, &t_set1);
 
       while(1){
                sleep(1);
                tv.tv_sec= 0;
                tv.tv_usec= 0;
                h= 0;
                printf("--------------->1");
                h= select(sockfd +1, &t_set1, NULL, NULL, &tv);
                printf("--------------->2");
 
                //if (h == 0) continue;
                if (h < 0) {
                        close(sockfd);
                        printf("在读取数据报文时SELECT检测到异常，该异常导致线程终止！\n");
                        return -1;
                };
 
                if (h > 0){
                        //memset(buf, 0, 4096);
                        //i= read(sockfd, buf, 4095);
                        memset(buf, 0, 4096);
                        i= read(sockfd, buf, 4095);
                        printf("%s\n", buf);
//**************************************我添加的*******************************************
//参考博文： https://blog.csdn.net/sinat_16643223/article/details/120241408

//似乎在计算md5的时候出现段错误 (核心已转储)

                         
                        char *user ="admin" ;
                        //char *user ="maxi" ; //尝试在这个版本的HTTP代码改下用户，发现还是没能改成帧率。
	                char *password ="123456" ;
                        char *realm ="Login to FH0427PAZ00039";
                        char *qop ="auth";
                        //char *nonce = "1555448628";
                        char nonc[10]={0};
                        char *nonce=nonc;
                        //char *nonce1="1298797490";//用来验证计算结果用的
                        //char *nonce = GetTargetStr(buf,"nonce=\"",'\"');
                        char *url ="/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20";
                        char *nc = "00000001";
                        //char *nc = "00000002";
                        char *algorithm = "MD5";
 
                        //char *cnonce = createRandomNum(32);//需要生成随机字符串
                        char *cnonce = createRandomNum(16);//需要生成随机字符串,感觉32位太长了
                        //char *cnonce = "522e610057899296"; //测试用

                        //似乎opaque没有用到。
                        
                        char Mystr1[50] = {0};
                        char *Mystr=Mystr1;
                        char *bufdizhi=buf;
                        char *nonce_name="nonce=";
                        char *nonce_namedizhi=nonce_name;
                        Mystr=strstr(bufdizhi,nonce_name);//这样确实提取出来了！！！
                       
                          //我还是直接用strncpy函数算了，字符串截取函数substr() substr("abcdef",1,3);//返回"bcd",从索引1处开始截取3个字符。
                       //其实借助于一些现有的字符串处理函数，自己写个提取解析也不难，包括现在去写串口解析是不是简单些？当然串口数据不是字符串，如果有相应现成的函数，也应该是方便许多。
                        //printf("提取出的nonce:");
                        printf("提取出的Mystr=%s ",Mystr);
                        int maxi=0;
                        for(maxi=7;maxi<16;maxi++)
                        {    
                       //   nonc[maxi-7]=Mystr1[maxi];                    
                      //    printf("%d",Mystr1[maxi]);
                        }
                        printf("\n");
                        nonce=substring(Mystr,7,10);
                        printf("提取出的nonce:%s",nonce);
                        printf("\n");
//段错误应该是出现在这里，GetTargetStr 函数,我实际用了下这个函数，很成问题。并不能真正得到。
/*********************************************************
                        char *realm = GetTargetStr(buf,"realm=\"",'\"');

 
                        char *nonce = GetTargetStr(buf,"nonce=\"",'\"');

 
                        char *algorithm = GetTargetStr(buf,"algorithm=",',');
 
                        char *qop = GetTargetStr(buf,"qop=\"",'\"');



                        char *url ="/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20";

                        //char response[33];

                        char *nc = "00000001";
 
                        char *cnonce = createRandomNum(32);//需要生成随机字符串
************************************************/
                        char A1[100] = {0};
 
                        sprintf(A1,"%s:%s:%s",user,realm,password);   

                        //char *md5_A1 = MD5_sign((unsigned char*)A1,strlen(A1)); //计算HA1
                        char *md5_A1;
                        md5_A1 =(char *)malloc(33);
                        md5_hash(A1,strlen(A1),md5_A1);
                 

                        char A2[100] = {0};
 
                        sprintf(A2,"GET:/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20");
 
                        //char *md5_A2 = MD5_sign((unsigned char*)A2,strlen(A2));  //计算HA2
                        char *md5_A2;
                        md5_A2 =(char *)malloc(33);
                        md5_hash(A2,strlen(A2),md5_A2);

                        char contact[200] = {0};
 
                        sprintf(contact,"%s:%s:%s:%s:%s:%s",md5_A1,nonce,nc,cnonce,qop,md5_A2);
                        //sprintf(contact,"%s:%s:%s:%s:%s:%s",md5_A1,nonce1,nc,cnonce,qop,md5_A2);//测试值的准确性用的
                        printf("计算出的HA1:%s\n",md5_A1);
                        printf("计算出的HA2:%s\n",md5_A2);
                        free(md5_A1);
                        free(md5_A2);

                        //char *response = MD5_sign((unsigned char*)contact,strlen(contact)); //得到response
                        char *response;
                        response=(char *)malloc(33); //不加上这句下面这句会出现段错误！
                        md5_hash(contact,strlen(contact),response);
                        printf("计算出的reponse:%s\n",response);

                        char WWW_Authenticate[1000] = {0};
 
                        char *format = "Authorization: Digest username=\"%s\",realm=\"%s\",qop=\"%s\",algorithm=\"%s\",uri=\"/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20\",nonce=\"%s\",nc=%s,cnonce=\"%s\",response=\"%s\",opaque=\"ecd96bfa32ed521cda6e9a8ed1701e6b3ef687d0\"";
                        //char *format = "Authenticate: Digest username=\"%s\",realm=\"%s\",qop=\"%s\",algorithm=\"%s\",uri=\"/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20\",nonce=\"%s\",nc=%s,cnonce=\"%s\",response=\"%s\",opaque=\"ecd96bfa32ed521cda6e9a8ed1701e6b3ef687d0\"";
                        //注意qop 和 nc 没有双引号，错了qop应该要带双引号，我看服务器返回的qop带双引号了，而且http文档里写的也带了。
                        sprintf(WWW_Authenticate,format,user,realm,qop,algorithm,nonce,nc,cnonce,response);//这应该是得到Authorization：后面的内容

                        printf("生成的Authentication:%s\n",WWW_Authenticate);
                        
                         //下面准备再发送http报文
                       memset(str1_1, 0, 4096);
                       strcat(str1_1, "GET /cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[0].Video.FPS=20 HTTP/1.1\n");
                       strcat(str1_1, "Host: 192.168.42.108\n");
                       strcat(str1_1,WWW_Authenticate);
                       strcat(str1_1, "\r\n\r\n");
                       printf("%s\n",str1_1);

                       ret = write(sockfd,str1_1,strlen(str1_1));
                       if (ret < 0) {
                       printf("发送失败！错误代码是%d，错误信息是'%s'\n",errno, strerror(errno));
                       exit(0);
                       }else{
                       printf("消息发送成功，共发送了%d个字节！\n\n", ret);
                       }
                
                         //下面是接收
                        memset(buf, 0, 4096);
                        i= read(sockfd, buf, 4095);
                        printf("服务器第二次响应报文：%s\n", buf);

//**************************************我添加的*******************************************
                        if (i==0){
                                close(sockfd);
                                printf("读取数据报文时发现远端关闭，该线程终止！\n");
                                return -1;
                        }
 
                        //printf("%s\n", buf);
                }
			//sleep(2);
        }
        close(sockfd);
 
 
        return 0;
}
